import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { type ProColumns, ProTable } from '@ant-design/pro-components';
import { Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
import PopconfirmButton from '@/components/PopconfirmButton';
import { projectDelete, projectList, userList } from '@/services/project';
import { progressOptions, statusOptions } from '../const/keys';
import AddModal from './AddModal';

//立项、交底、布线、木工底、完成面检查、安装、调试、调试报告、交付

const App = () => {
  const [open, setOpen] = useState(false);
  const [id, setId] = useState<number | undefined>(undefined);
  const myTable = useRef<any>(null);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [userOptions, setUserOptions] = useState<
    Array<{ label: string; value: number }>
  >([]);
  const handleEdit = (record: any) => {
    // 编辑逻辑
    setOpen(true);
    setId(record.id);
  };
  const handleDelete = async (record: any) => {
    // 删除逻辑
    await projectDelete(record.id);
    myTable.current?.reload();
  };
  const columns: ProColumns<Record<string, any>, 'text'>[] | undefined = [
    //序号
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      valueType: 'indexBorder',
      fixed: 'left',
      width: 60,
      render: (_text, _record, index) => {
        return (pageNum - 1) * pageSize + index + 1;
      },
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
    },
    //签订时间
    {
      title: '签订时间',
      dataIndex: 'signingTime',
      key: 'signingTime',
      valueType: 'date',
      search: false,
    },
    //业务经理
    {
      title: '业务经理',
      dataIndex: 'businessManagerUserId',
      key: 'businessManagerUserId',
      //接口获取,下拉，搜索 userList()
      valueType: 'select',
      fieldProps: {
        options: userOptions,
        // showSearch: true,
        // filterOption: (input: any, option: { label: string | any[] }) =>
        //   option?.label?.includes(input) || false,
      },
      render: (_text, record) => {
        return record.businessManagerUserName || '-';
      },
    },
    //项目经理
    {
      title: '项目经理',
      dataIndex: 'projectManagerUserId',
      key: 'projectManagerUserId',
      valueType: 'select',
      fieldProps: {
        options: userOptions,
        // showSearch: true,
        // filterOption: (input: any, option: { label: string | any[] }) =>
        //   option?.label?.includes(input) || false,
      },
      render: (_text, record) => {
        return record.projectManagerUserName || '-';
      },
    },

    //总金额
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      search: false,
      render: (_text, record) => {
        return (record.totalAmount / 100)?.toFixed(2) || '-';
      },
    },
    //项目进度
    {
      title: '项目进度',
      dataIndex: 'projectProgress',
      key: 'projectProgress',
      valueType: 'select',
      fieldProps: {
        options: progressOptions,
      },
      render: (_text, record) => {
        return progressOptions.find(
          (item) => item.value === record.projectProgress,
        )?.label;
      },

      //必填
    },
    //状态
    {
      title: '状态',
      dataIndex: 'projectStatus',
      key: 'projectStatus',
      valueType: 'select',
      fieldProps: {
        options: statusOptions,
      },
      render: (_text, record) => {
        return statusOptions.find((item) => item.value === record.projectStatus)
          ?.label;
      },
    },
    //操作 编辑，删除
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      width: 150,
      render: (_text, record) => [
        <Button
          icon={<EditOutlined />}
          key="edit"
          size="small"
          type="link"
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <PopconfirmButton
          title={`确定要删除 ${record.projectName} 吗？`}
          icon={<DeleteOutlined />}
          key="delete"
          type="link"
          size="small"
          danger={false}
          onConfirm={() => {
            handleDelete(record);
          }}
        >
          删除
        </PopconfirmButton>,
      ],
    },
  ];
  const fetchUserList = async () => {
    const { data } = await userList();
    setUserOptions(
      data.map((item: { id: number; showText: string }) => ({
        label: item.showText,
        value: item.id,
      })),
    );
  };
  useEffect(() => {
    console.clear();
    fetchUserList();
  }, []);
  return (
    <>
      <ProTable
        actionRef={myTable}
        columns={columns}
        scroll={{
          x: 1000,
        }}
        search={{
          defaultCollapsed: false,
        }}
        request={async (params = {}) => {
          const { rows, total } = await projectList({
            ...params,
            pageNum,
            pageSize,
          });

          return { data: rows, total };
        }}
        toolBarRender={() => [
          <Button
            ghost
            icon={<PlusOutlined />}
            key={'add'}
            size="small"
            type="primary"
            onClick={() => setOpen(true)}
          >
            新增
          </Button>,
        ]}
        pagination={{
          showSizeChanger: true,
          pageSize,
          current: pageNum,
          onChange: (page, size) => {
            setPageNum(page);
            setPageSize(size);
          },
        }}
      />
      {open ? (
        <AddModal
          id={id}
          onClose={(reflash) => {
            setId(undefined);
            setOpen(false);
            if (reflash) {
              myTable.current?.reload();
            }
          }}
        />
      ) : null}
    </>
  );
};
export default App;
